package com.tianruan.psychological.moduls.sys.user.api;

import com.tianruan.psychological.common.constant.GlobalExceptionEnum;
import com.tianruan.psychological.common.response.VResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2019-11-26 18:28
 * @PS
 */
@RestController
public class LoginController {

    @Autowired(required = false)
    private TokenStore redisTokenStore;

    /**
     * 退出登录，清除token
     * @param principal
     * @param request
     * @param response
     */
    @GetMapping("/oauth/logout")
    public VResponse<Object> logout(Principal principal,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
        OAuth2AccessToken accessToken = redisTokenStore.getAccessToken(oAuth2Authentication);
        redisTokenStore.removeAccessToken(accessToken);
        redisTokenStore.removeAccessTokenUsingRefreshToken(accessToken.getRefreshToken());
        redisTokenStore.removeRefreshToken(accessToken.getRefreshToken());
        return VResponse.success(GlobalExceptionEnum.LOGOUT_SUCCESS);
    }

}
